package br.usjt.servico;


import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//
public class MySQLClienteDAO implements IClienteDAO {
	private static final String cadastraCliente = "INSERT INTO cliente "
			+ "(cpf, nome, endereco, telefone) VALUES ( ?, ?,?,? ) ";
	private static final String excluiCliente = "DELETE FROM cliente WHERE "
			+ "cpf = ? ";
	private static final String consultaCliente = "SELECT *  FROM cliente WHERE "
			+ "cpf = ? ";
	private static final String consultaNome = "SELECT *  FROM cliente WHERE "
			+ "nome LIKE ? ";
	private static final String alterarDados = "UPDATE cliente SET nome = ? "
			+ ", endereco = ?, telefone=? WHERE cpf = ? ";
	String msg = "";

	@Override
	public ResultSet consulta(String cpf) {
		ResultSet rs = null;
		PreparedStatement stmt;
		try {

			stmt = MySQLDAOFactory.criaConexao().prepareStatement(consultaCliente);
			stmt.setString(1, cpf);
			rs = stmt.executeQuery();
			// stmt.close();
		} catch (SQLException e) {
			
			msg = e.getMessage();
			System.out.println(msg);
		}
		return rs;
	}
	@Override
	public ResultSet consultaNome(String nome) {
		ResultSet rs = null;
		PreparedStatement stmt;
		try {

			stmt = MySQLDAOFactory.criaConexao().prepareStatement(consultaNome);
			stmt.setString(1, nome);

			rs = stmt.executeQuery();
			
			// stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
		}
		return rs;
	}
	
	@Override
	public int cadastra(String cpf, String nome, String endereco, String telefone) {
		PreparedStatement stmt;
		int rc = 0;
		try {
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(cadastraCliente);
			stmt.setString(1, cpf);
			stmt.setString(2, nome);
			stmt.setString(3, endereco);
			stmt.setString(4, telefone);

			rc = stmt.executeUpdate();
			stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
		}
		return rc;
	}
	

	@Override
	public int exclui(String cpf) {
		PreparedStatement stmt;
		int rc = 0;
		try {
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(excluiCliente);
			stmt.setString(1, cpf);
			rc = stmt.executeUpdate();
			
			stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
		}
		return rc;
	}

	@Override
	public int altera(String cpf, String nome, String endereco, String telefone) {
		PreparedStatement stmt;
		int rc = 0;
		try {
			stmt = MySQLDAOFactory.criaConexao().prepareStatement(alterarDados);
			
			stmt.setString(1, nome);
			stmt.setString(2, endereco);
			stmt.setString(3, telefone);
			stmt.setString(4, cpf);
			rc = stmt.executeUpdate();
			stmt.close();
		} catch (SQLException e) {
			msg = e.getMessage();
		}
		return rc;
	}

	public String getMessage() {
		return msg;
	}
}
